package com.commerce.interceptor;

import com.commerce.enums.ErrorCode;
import com.commerce.exception.ResultException;
import com.commerce.util.JwtUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("utf-8");
        String token = request.getHeader("access_token");
        //token不存在
        if (null != token) {
            //验证token是否正确
            boolean result = JwtUtil.verify(token);
            if (result) {
                return true;
            }
        }
        if (token == null) {
            throw new ResultException(ErrorCode.TOKEN_IS_EMPTY);
        }
        if (JwtUtil.verify(token) && JwtUtil.isExpired(token)) {
            throw new ResultException(ErrorCode.TOKEN_IS_EXPIRED);
        }

        if (!JwtUtil.verify(token)) {
            throw new ResultException(ErrorCode.TOKEN_IS_ILLEGAL);
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
